

package com.io.aop;


import com.io.constant.Constant;
import com.io.entity.SysUserEntity;
import com.io.exception.SelfException;
import com.io.service.SysDeptService;
import com.io.service.SysRoleDeptService;
import com.io.service.SysUserRoleService;
import com.io.utils.annotation.DataFilter;
import com.io.utils.shiro.ShiroUtils;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * The class/interface 数据过滤
 *
 * @author guod
 * @version 1.0 use jdk 1.8
 */
@Aspect
@Component
@SuppressWarnings("unchecked")
public class DataFilterAspect {
    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysRoleDeptService sysRoleDeptService;

    @Pointcut("@annotation(com.io.utils.annotation.DataFilter)")
    public void dataFilterCut() {
    }

    @Before("dataFilterCut()")
    public void dataFilter(JoinPoint point) {
        Object params = point.getArgs()[0];
        if (params instanceof Map) {
            SysUserEntity user = ShiroUtils.getUserEntity();
            // 如果不是超级管理员，则进行数据过滤
            if (user.getId() != Constant.SUPER_ADMIN) {
                Map<String, Object> map = (Map<String, Object>) params;
                map.put(Constant.SQL_FILTER, getSQLFilter(user, point));
            }
            return;
        }
        throw new SelfException("数据权限接口，只能是Map类型参数，且不能为NULL");
    }

    /**
     * 获取数据过滤的SQL
     */
    private String getSQLFilter(SysUserEntity user, JoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        DataFilter dataFilter = signature.getMethod().getAnnotation(DataFilter.class);
        // 获取表的别名
        String tableAlias = dataFilter.tableAlias();
        if (StringUtils.isNotBlank(tableAlias)) {
            tableAlias += ".";
        }

        // 部门ID列表
        Set<Long> deptIdList = new HashSet<>();

        // 用户角色对应的部门ID列表
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(user.getUserId());
        if (roleIdList.size() > 0) {
            List<Long> userDeptIdList = sysRoleDeptService.queryDeptIdList(roleIdList.toArray(new Long[0]));
            deptIdList.addAll(userDeptIdList);
        }

        // 用户子部门ID列表
        if (dataFilter.subDept()) {
            List<Long> subDeptIdList = sysDeptService.getSubDeptIdList(user.getDeptId());
            deptIdList.addAll(subDeptIdList);
        }

        StringBuilder sqlFilter = new StringBuilder();
        sqlFilter.append(" (");

        if (deptIdList.size() > 0) {
            sqlFilter.append(tableAlias).append(dataFilter.deptId()).append(" in(").append(StringUtils.join(deptIdList, ",")).append(")");
        }

        // 没有本部门数据权限，也能查询本人数据
        if (dataFilter.user()) {
            if (deptIdList.size() > 0) {
                sqlFilter.append(" or ");
            }
            sqlFilter.append(tableAlias).append(dataFilter.userId()).append("=").append(user.getUserId());
        }

        sqlFilter.append(")");

        if (sqlFilter.toString().trim().equals("()")) {
            return null;
        }

        return sqlFilter.toString();
    }
}
